//获取应用实例
const app = getApp()
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
var init
Page({
    data: {
      report:{},
      reportId:"",
      username:"",
      boxId:"",
      score_item:"",
      raw_fileUrls:[],
      imageUrl:"",
      videoUrl:"",
      noRecordShow: true, //初始显示
      recordLuzhiShow: false, //控制录制
      finishRecordShow: false, //完成录音
      extistRecordShow: false, //已存在录音
      playAudioShow: false, //播放按钮
      exisiFilePath: '', //已经存在的录音
      countNume: 0, // 倒计时
      filePath: '', // 临时语音录制文件
      duration: 0, // 录制时间
      score:'',//分数
      r_comment:"",//评语,
      ai_r_comment:"",
      tempFilePath:"",
      showConfirm:false,
      resourceIndex:0,
      isShowKeyboard:false,
      keys:[1,2,3,4,'后退',5,6,7,8,9,0,'A','B','C','D','E','F','+','-','确认'],
      text:"长按录音频评语",
      report_text:"",
       article:{}
    },
    onLoad: function(options) {
      var that=this;
      if (options != null){
        const {username,score_item,boxId}= options;
        this.setData({username,score_item,boxId})
        wx.request({
          url: app.globalData.url+'/wechat/user_report?username='+username+"&boxId="+boxId+"&score_item="+score_item,
          method: 'get',
          success: res2 => {
            const raw_fileUrls=res2.data&&res2.data.raw_fileUrls||[];
            const image=raw_fileUrls.find(f=>f.type==="image");
            const video=raw_fileUrls.find(f=>f.type==="video");
            const dataInfo=raw_fileUrls.find(f=>f.type==="text");
            const r_comment=res2.data&&res2.data.r_comment;
            const ai_r_comment=res2.data&&res2.data.ai_r_comment;
            console.log("ai_r_comment",ai_r_comment)
            let obj = app.towxml(ai_r_comment,'markdown',{
              theme:'light', //主题 dark 黑色，light白色，不填默认是light
              base:"www.xxx.com",
          events:{      //为元素绑定的事件方法
           tap:e => {
            console.log('tap',e);
           },
           change:e => {
            console.log('todo',e);
           }
          }
         });
            that.setData({
              report:res2.data||{},
              raw_fileUrls,
              imageUrl:image&&image.url,
              videoUrl:video&&video.url,
              score:res2.data&&res2.data.r_score,
              r_comment,
              ai_r_comment,
              exisiFilePath:res2.data&&res2.data.audio_url,
              extistRecordShow:res2.data&&res2.data.audio_url?true:false,
              noRecordShow:res2.data&&res2.data.audio_url?false:true,
              reportId:res2.data&&res2.data.objectId,
              filePath:res2.data&&res2.data.audio_url,
              report_text:dataInfo&&dataInfo.data
            });
          
            wx.setNavigationBarTitle({
              title: res2.data&&res2.data.score_item+"_"+username||"实验"
          })
          
          //更新解析数据
       this.setData({
        article:obj,
       });

          console.log("r_comment",this.data.r_comment)
          }
        })
        
      }
  

    },

    copyContent: function (event) {
      const content = event.currentTarget.dataset.content; // 获取需要复制的内容
      console.log("content",content)
      wx.setClipboardData({
        data: content,
        success: function () {
          wx.showToast({
            title: '内容已复制',
          });
        }
      });
    },
    addImage:function(){
      const that=this;
      wx.chooseMedia({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        mediaType:["image"],
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFile = res.tempFiles[0];
          that.setData({tempFilePath:tempFile.tempFilePath});
          that.upload(tempFile.tempFilePath,tempFile.fileType)
        },
      })
    },

    showDeleteImageConfirm:function(){
      wx.showModal({
        title: '提示',
        content: '确定删除该图片？',
        success: (res) => {
          if (res.confirm) {
            this.removeResource('image')
          }
        }
      })
    },
    showDeleteVideoConfirm:function(){
      wx.showModal({
        title: '提示',
        content: '确定删除该视频？',
        success: (res) => {
          if (res.confirm) {
            this.removeResource('video')
          }
        }
      })
    },

    addVideo:function(){
      const that=this;
      wx.chooseMedia({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        mediaType:["video"],
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFile = res.tempFiles[0];
          that.setData({tempFilePath:tempFile.tempFilePath});
          that.upload(tempFile.tempFilePath,tempFile.fileType)
        },
      })
    },

    upload:function(tempFilePath,type){
      const that=this;
      console.log('tempFilePath',tempFilePath)
      wx.request({
        url: app.globalData.url + '/wechat/qiniu_upload_token',
        method: 'get',
        success: res => {
          const uploadTask = wx.uploadFile({
            url: res.data.url,
            header: { 'content-type': 'multipart/form-data' },
            method: 'POST',
            filePath: tempFilePath,
            name: 'file',
            formData: {
              'token': res.data.upload_token
            },
            success: function (res2) {
              const data = JSON.parse(res2.data);
              const fileurl=res.data.qiniu_domain+data.key;
              const raw_fileUrls=that.data.raw_fileUrls;
              raw_fileUrls.push({type,url:fileurl});
             wx.request({
                url: app.globalData.url+'/wechat/update_report',
                data: {
                  id: that.data.reportId,
                  key:"raw_fileUrls",
                  value:raw_fileUrls,
                  token:app.globalData.token,
            },
            method: 'POST',
             header: {
              'content-type': 'application/json'
             },
            success: res2 => {
              switch (type) {
                case "image": {
                  that.setData({
                    imageUrl:fileurl,
                });
                    break;
                }
                case "video": {
                  that.setData({
                    videoUrl:fileurl,
                });
                    break;
                }
    
            }
              that.setData({
                report:res2.data||{},
                raw_fileUrls,
            });
          }
        })
            },
            fail: function (err) {
              console.log(err);
              wx.showToast({
                title: '上传失败，图片服务器出错：' + err.errMsg,
                icon: 'none',
                duration: 2000
              })
            },
          })
          uploadTask.onProgressUpdate((res) => {
            if (res.progress == 100) {
              wx.showToast({
                title: '上传成功！',
                icon: 'success',
                duration: 2000
              })
            }
          })
        },
        fail: function (err) {
          console.log(err);
          wx.showToast({
            title: '上传失败，获取token出错：' + err,
            icon: 'none',
            duration: 2000
          })
        }
      });
    },
    showDialog:function(e){
      const index=e.target.id
      this.setData({showConfirm:true,resourceIndex:index})
    },
    closeDialog:function(){
      this.setData({showConfirm:false})
    },
    removeResource:function(type){
      const that=this;
      const raw_fileUrls=this.data.raw_fileUrls;
      const _raw_fileUrls= raw_fileUrls.filter(f=>f.type!==type);
      wx.request({
        url: app.globalData.url+'/wechat/update_report',
        data: {
          id: that.data.reportId,
          key:"raw_fileUrls",
          value:_raw_fileUrls,
          token:app.globalData.token
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: res2 => {
          switch (type) {
            case "image": {
              this.setData({
                imageUrl:"",
            });
                break;
            }
            case "video": {
              this.setData({
                videoUrl:"",
            });
                break;
            }

        }
          this.setData({
            report:res2.data||{},
            raw_fileUrls:_raw_fileUrls,
          });
        }
      })
    },
    upResource:function(e){
      const that=this;
      const idx=e.target.id;
      const raw_fileUrls=this.data.raw_fileUrls;
      if (idx <= 0) {
        return;
    }
    const oResource=raw_fileUrls[idx];
    raw_fileUrls.splice(idx, 1);//删除原id
    raw_fileUrls.splice(idx - 1, 0, oResource);
    wx.request({
      url: app.globalData.url+'/wechat/update_report',
      data: {
        id: that.data.reportId,
        key:"raw_fileUrls",
        value:raw_fileUrls,
        token:app.globalData.token
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: res2 => {
        this.setData({
          report:res2.data||{},
          raw_fileUrls:raw_fileUrls,
          showConfirm:false
        });
      }
    })
    },
    downResource:function(e){
      const that=this;
      const idx=e.target.id;
      const raw_fileUrls=this.data.raw_fileUrls
        if (idx >= raw_fileUrls.length - 1) {
            return;
        }
        const oResource=raw_fileUrls[idx];
        raw_fileUrls.splice(idx, 1);//删除原id
        raw_fileUrls.splice(idx + 1, 0, oResource);
        wx.request({
          url: app.globalData.url+'/wechat/update_report',
          data: {
            id: that.data.reportId,
            key:"raw_fileUrls",
            value:raw_fileUrls,
            token:app.globalData.token
          },
          method: 'POST',
          header: {
            'content-type': 'application/json'
          },
          success: res2 => {
            this.setData({
              report:res2.data||{},
              raw_fileUrls:raw_fileUrls,
              showConfirm:false
            });
          }
        })
    },
   
      // 语音授权
  authorize() {
    wx.authorize({
      scope: 'scope.record',
      success() {
        // that.stratRecordAudio()
      },
      fail() {
        wx.showModal({
          title: '提示',
          content: '您未授权录音，功能将无法使用',
          showCancel: true,
          confirmText: "授权",
          confirmColor: "#2D59DF",
          success: function (res) {
            if (res.confirm) {
              //确认则打开设置页面（重点）
              wx.openSetting({
                success: (res) => {
                  if (!res.authSetting['scope.record']) {
                    //未设置录音授权
                    wx.showModal({
                      title: '提示',
                      content: '您未授权录音，功能将无法使用',
                      showCancel: false,
                      success: function (res) {},
                    })
                  } else {
                    // that.stratRecordAudio()
                  }
                },
                fail: function () {
                  console.log("授权设置录音失败");
                }
              })
            } else if (res.cancel) {
              console.log("cancel");
            }
          },
          fail: function () {
            console.log("openfail");
          }
        })
      }
    })
  },

  //录音计时器
  recordingTimer: function (time) {
    var that = this
    if (time == undefined) {
      //将计时器赋值给init
      init = setInterval(function () {
        var time = that.data.countNume + 1;
        that.setData({
          countNume: time
        })
      }, 1000);
    } else {
      clearInterval(init)
    }
  },
    // 开始录音
    stratRecordAudio() {
      const that =this;
      wx.getSetting({
        success: function(res) {
          var auth = res.authSetting['scope.record'];
          if (auth === undefined) {
            that.authorize()
          } else if (auth === false) {
            that.authorize()
          } else {
            recorderManager.onStart((res) => {
              that.setData({text:"录音中"})
            })
            recorderManager.onStop((res) => {
              console.log("stratRecordAudio",res.tempFilePath)
              if(res.tempFilePath){
                this.setData({
                  // recordLuzhiShow: false,
                  finishRecordShow: true,
                  filePath: res.tempFilePath,
                  duration: res.duration,
                })
              }
            })
            const options = {
              duration: that.data.duration, //指定录音的时长，单位 ms
              sampleRate: 16000, //采样率
              numberOfChannels: 1, //录音通道数
              encodeBitRate: 96000, //编码码率
              format: 'mp3', //音频格式，有效值 aac/mp3
              frameSize: 50, //指定帧大小，单位 KB
            }
            that.recordingTimer()
            recorderManager.start(options)
          }
        }
      });
      
    },
  
    // 停止录音
    stopRecordAudio() {
      recorderManager.onStop((res) => {
        console.log('stopRecordAudio',res.tempFilePath)
        if(res.tempFilePath){
          this.setData({
            filePath: res.tempFilePath,
            duration: res.duration,
            text: '长按录音频评语',
          finishRecordShow: true,
          noRecordShow:false
          })
        }
        
      })
      this.recordingTimer(this.data.countNume)
      recorderManager.stop()
    },
    playRecordAudio(e) {
      //在ios下静音时播放没有声音，默认为true，改为false就好了。
      innerAudioContext.obeyMuteSwitch = false
      var filPathType = e.currentTarget.dataset.type
      console.log('filPathType',filPathType)
      if (filPathType == 1) {
        this.setData({
          playAudioShow: true,
          extistRecordShow:false,
          finishRecordShow: false
        })
        innerAudioContext.src = this.data.filePath;
        console.log("this.data.filePath",this.data.filePath)
        innerAudioContext.play()
        innerAudioContext.onEnded(() => {
          this.setData({
            playAudioShow: false,
            finishRecordShow: true,
          extistRecordShow: true
          })
        })
      } else {
        this.setData({
          playAudioShow: true,
          extistRecordShow: false
        })
        innerAudioContext.src = this.data.exisiFilePath
        innerAudioContext.play()
        innerAudioContext.onEnded(() => {
          this.setData({
            playAudioShow: false,
            extistRecordShow: true
          })
        })
      }
     
    },
  
    // 重新录音
    recycleRecordAudio() {
      console.log("recycleRecordAudio")
      var that = this
      wx.showModal({
        title: "重新录音",
        content: "是否重新录制?",
        success(res) {
          if (res.confirm) {
            that.setData({
              noRecordShow: true, //初始显示
              recordLuzhiShow: false, //控制录制
              finishRecordShow: false, //完成录音
              extistRecordShow: false, //已存在录音
              playAudioShow: false, //播放按钮
              filePath: '',
              countNume: 0,
              duration: 0
            })
            innerAudioContext.stop()
          }
        }
      })
    },
      // 删除语音
      showDeleteRecordConfirm() {
    console.log("deleteRecord")
    var that = this
    wx.showModal({
      title: '提示',
      content: '确定要删除语音吗?',
      success(res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.url+'/wechat/update_report',
            data: {
              id: that.data.reportId,
              key:"audio_url",
              value:null,
              token:app.globalData.token
            },
            method: 'POST',
            header: {
              'content-type': 'application/json'
            },
            success: res2 => {
              const report=that.data.report;
              that.setData({report,noRecordShow:true,finishRecordShow:false,filePath:null,extistRecordShow:false})
                wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
                })
            }
          })
          // deleteRecording(that.data.id).then(res => {
          
          // })
        }
      }
    })
  },

  change_score:function(e){
    this.setData({
      score: e.detail.value
    })
  },

  change_r_comment:function(e){
    this.setData({
      r_comment: e.detail.value
    })
  },

  showKeyboard:function(e){
    const value=!this.data.isShowKeyboard;
    this.setData({isShowKeyboard:value})
    wx.pageScrollTo({
      scrollTop: 9999, // 设置为一个足够大的值，保证能够滚动到最底部
      // duration: 300 // 可选参数，滚动时间，默认300ms
    })
    
  },
  hideKeyboard:function(){
        this.setData({isShowKeyboard:false})
  },

  clickBoard:function(e){
    const key=e.target.id;
    const text = this.data.score||'';
    const reg = /[a-zA-Z0-9]/;
    let newText = text;
    if (reg.test(key)||key=='+'||key=="-") {
        newText = text + (key + '');
        this.setData({score:newText})
    } else {
        switch (key) {
            case "后退": {
                newText = text.substring(0, text.length - 1);
                this.setData({score:newText})
                break;
            }
            case "确认": {
                this.onOK(newText);
                break;
            }

        }
    }
  
  },
  onOK:function(score){
    wx.request({
      url: app.globalData.url+'/wechat/update_report',
      data: {
        id: this.data.reportId,
        key:"r_score",
        value:score,
        token:app.globalData.token,
  },
  method: 'POST',
   header: {
    'content-type': 'application/json'
   },
  success: res2 => {
    this.setData({isShowKeyboard:false})
}
})
  },

  saveScore:function(){
      // 将临时语音上传到七牛
      const that=this;
      console.log(that.data.filePath);
      const filePath=this.data.filePath;
      if(!filePath){
        wx.request({
          url: app.globalData.url+'/wechat/save_score',
          data: {
            id: that.data.reportId,
            r_score:that.data.score,
            r_comment:that.data.r_comment,
            scoreTeacher:app.globalData.localuserinfo.username,
            token:app.globalData.token
      },
      method: 'POST',
       header: {
        'content-type': 'application/json'
       },
      success: res2 => {
        wx.navigateTo({
          url: "../teacher_current_reports/teacher_current_reports?boxId="+this.data.boxId+"&score_item="+this.data.score_item,
      });
    }
  })
      }else
      wx.request({
        url: app.globalData.url + '/wechat/qiniu_upload_token',
        method: 'get',
        success: res => {
          console.log(res.data);
          const uploadTask = wx.uploadFile({
            url: res.data.url,
            header: { 'content-type': 'multipart/form-data' },
            method: 'POST',
            filePath: that.data.filePath,
            name: 'file',
            formData: {
              'token': res.data.upload_token
            },
            success: function (res2) {
              const data = JSON.parse(res2.data);
              const audio_url=res.data.qiniu_domain+data.key;
             wx.request({
                url: app.globalData.url+'/wechat/save_score',
                data: {
                  id: that.data.reportId,
                  audio_url:audio_url,
                  r_score:that.data.score,
                  r_comment:that.data.r_comment,
                  scoreTeacher:app.globalData.localuserinfo.username,
                  token:app.globalData.token
            },
            method: 'POST',
             header: {
              'content-type': 'application/json'
             },
            success: res3 => {
              wx.navigateTo({
                url: "../teacher_current_reports/teacher_current_reports?boxId="+that.data.boxId+"&score_item="+that.data.score_item,
            });
          }
        })
            },
            fail: function (err) {
              console.log(err);
              wx.showToast({
                title: '语音上传失败：' + err.errMsg,
                icon: 'none',
                duration: 2000
              })
              that.setData({
                loading: false
              })
            },
          })
          uploadTask.onProgressUpdate((res) => {
            if (res.progress == 100) {
              wx.showToast({
                title: '上传成功！',
                icon: 'success',
                duration: 2000
              })
              that.setData({
                loading: false
              })
            }
          })
        },
        fail: function (err) {
          console.log(err);
          wx.showToast({
            title: '上传失败，获取token出错：' + err,
            icon: 'none',
            duration: 2000
          })
          that.setData({
            loading: false
          })
        }
      });
  },
  onHide() {
  
  },
})

